#include "mongoc_const.h"
#include "mongoc_data.h"

int write_zlev(int cid, int nlev, double z[]) {
  if (cid >= nbundle) {
    return FORTRAN_MONGO_NO_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[cid];

  bson_error_t error;
  bson_t doc;
  bson_t child;
  char key[3];

  bson_init(&doc);
  bson_init(&child);
  bson_append_array_begin(&doc, "zlev", -1, &child);
  for (int k = 0; k < nlev; ++k) {
    sprintf(key, "%d", k);
    BSON_APPEND_DOUBLE(&child, key, z[k]);
  }
  bson_append_array_end(&doc, &child);
  if (!mongoc_collection_insert_one(bundle->col, &doc, NULL, NULL, &error)) {
    fprintf(stderr, "[Error]: Failed to insert data: %s\n", error.message);
    return EXIT_FAILURE;
  }

  return FORTRAN_MONGO_NO_ERROR;
}

int write_band_wdir(int cid, int nband_wdir, double band_wdir[]) {
  if (cid >= nbundle) {
    return FORTRAN_MONGO_NO_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[cid];

  bson_error_t error;
  bson_t doc;
  bson_t child;
  char key[3];

  bson_init(&doc);
  bson_init(&child);
  bson_append_array_begin(&doc, "band_wdir", -1, &child);
  for (int k = 0; k < nband_wdir; ++k) {
    sprintf(key, "%d", k);
    BSON_APPEND_DOUBLE(&child, key, band_wdir[k]);
  }
  bson_append_array_end(&doc, &child);
  if (!mongoc_collection_insert_one(bundle->col, &doc, NULL, NULL, &error)) {
    fprintf(stderr, "[Error]: Failed to insert data: %s\n", error.message);
    return EXIT_FAILURE;
  }

  return FORTRAN_MONGO_NO_ERROR;
}

int write_band_wsp(int cid, int nband_wsp, double band_wsp[]) {
  if (cid >= nbundle) {
    return FORTRAN_MONGO_NO_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[cid];

  bson_error_t error;
  bson_t doc;
  bson_t child;
  char key[3];

  bson_init(&doc);
  bson_init(&child);
  bson_append_array_begin(&doc, "band_wsp", -1, &child);
  for (int k = 0; k < nband_wsp; ++k) {
    sprintf(key, "%d", k);
    BSON_APPEND_DOUBLE(&child, key, band_wsp[k]);
  }
  bson_append_array_end(&doc, &child);
  if (!mongoc_collection_insert_one(bundle->col, &doc, NULL, NULL, &error)) {
    fprintf(stderr, "[Error]: Failed to insert data: %s\n", error.message);
    return EXIT_FAILURE;
  }

  return FORTRAN_MONGO_NO_ERROR;
}
